package com.dxf.redis.distributedlock;

import redis.clients.jedis.Jedis;


/**
 * @author duxvfeng  version 1
 *  运用redis 的setnx
 *
 */
public class RedisLockCopy implements Lock{


    static {
        jedis = new Jedis("192.168.10.113", 6379);

    }
    private static final Jedis jedis;

    private static final long expiressTime=10000;


    @Override
    public boolean lock(String uuid) {

        long expires = System.currentTimeMillis()+expiressTime;
        String expTime = String.valueOf(expires);


        long setnx = jedis.setnx("dis-lock", uuid+"-"+expTime);

        boolean flag = false;
        if(setnx==1) {
            flag=true;
            String s = jedis.get("dis-lock").split("-")[1];
            if(s != null && Long.valueOf(s) <System.currentTimeMillis()){
                String oldValue = jedis.getSet("dis-lock", expTime).split("-")[1];
                if (s !=null && s==oldValue){ //CAS思想
                    flag = true;
                }
            }
        }
        return flag;
    }

    @Override
    public boolean lock(String uuid, long exTime) {
        return false;
    }

    @Override
    public boolean unlock(String uuid) {
        String s = jedis.get("dis-lock").split("-")[0];
        if(uuid.equals(s)){
        long del = jedis.del("dis-lock");
            if(del >=1) return true;
        }
        return false;
    }


}
